package com.summer_administration.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.summer_administration.exception.BusinessException;
import com.summer_administration.mapper.CommuneArrangeMapper;
import com.summer_administration.mapper.GroupeMapper;
import com.summer_administration.mapper.MaterialMapper;
import com.summer_administration.pojo.CommuneArrange;
import com.summer_administration.pojo.PageBean;
import com.summer_administration.service.CommuneArrangeService;
import com.summer_administration.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class CommuneArrangeServiceImpl implements CommuneArrangeService {
    private static final Pattern PRIZE_PATTERN = Pattern.compile("^(\\d+)个(.+)$");

    @Autowired
    private CommuneArrangeMapper communeArrangeMapper;
    @Autowired
    private MaterialMapper materialMapper;

    @Autowired
    private GroupeMapper groupeMapper;

    @Override
    @Transactional
    public void add(CommuneArrange arrange) {
        validatePrizeFormat(arrange.getPrize());
        updateMaterialStock(arrange.getPrize(), false);

        arrange.setCreateTime(LocalDateTime.now());
        arrange.setUpdateTime(LocalDateTime.now());

        // 修改点1：添加类型检查和空值处理
        Map<String, Object> userInfo = ThreadLocalUtil.get();
        if (userInfo == null || userInfo.get("id") == null) {
            throw new BusinessException("用户未登录或登录信息不完整");
        }
        arrange.setCreateUser((Integer) userInfo.get("id"));

        // 新增一个根剧小组名字查询小组id
        String groupeName = arrange.getGroupName();
        String groupId = groupeMapper.findGroupIdByGroupName(groupeName);
        arrange.setGroupId(groupId);

        communeArrangeMapper.add(arrange);
    }

    @Override
    public PageBean<CommuneArrange> list(Integer pageNum, Integer pageSize) {
        PageBean<CommuneArrange> pb = new PageBean<>();
        PageHelper.startPage(pageNum, pageSize);

        // 修改点2：添加类型检查和空值处理
        Map<String, Object> userInfo = ThreadLocalUtil.get();
        if (userInfo == null || userInfo.get("id") == null) {
            throw new BusinessException("用户未登录或登录信息不完整");
        }
        Integer userId = (Integer) userInfo.get("id");

        Page<CommuneArrange> page = (Page<CommuneArrange>) communeArrangeMapper.list(userId);

        //pb.setTotal(page.getTotal());
        pb.setItems(page.getResult());
        return pb;
    }

    @Override
    @Transactional
    public void update(CommuneArrange arrange) {
        // 获取原始数据
        CommuneArrange original = communeArrangeMapper.getById(arrange.getId());
        if (original == null) {
            throw new BusinessException("要更新的社区安排不存在");
        }

        // 恢复旧库存
        updateMaterialStock(original.getPrize(), true);

        // 验证并扣减新库存
        validatePrizeFormat(arrange.getPrize());
        updateMaterialStock(arrange.getPrize(), false);

        arrange.setUpdateTime(LocalDateTime.now());

        // 新增一个根剧小组名字查询小组id
        String groupeName = arrange.getGroupName();
        String groupId = groupeMapper.findGroupIdByGroupName(groupeName);
        arrange.setGroupId(groupId);
        communeArrangeMapper.update(arrange);
    }

    @Override
    @Transactional
    public void delete(Integer id) {
        CommuneArrange arrange = communeArrangeMapper.getById(id);
        if (arrange == null) {
            throw new BusinessException("要删除的社区安排不存在");
        }
        updateMaterialStock(arrange.getPrize(), true);
        communeArrangeMapper.delete(id);
    }

    @Override
    public List<CommuneArrange> getByGroupId(String groupId) {
        return communeArrangeMapper.getByGroupIdOrderByTime(groupId);
    }

    @Override
    public String checkConflict(String groupId) {
        List<CommuneArrange> arranges = communeArrangeMapper.getByGroupIdOrderByTime(groupId);
        if (arranges.size() < 2) return "无冲突";

        for (int i = 1; i < arranges.size(); i++) {
            LocalDateTime prevEnd = arranges.get(i-1).getTime().plusHours(2);
            if (arranges.get(i).getTime().isBefore(prevEnd)) {
                return String.format("%s与%s存在时间冲突",
                        arranges.get(i-1).getCommune(),
                        arranges.get(i).getCommune());
            }
        }
        return "无冲突";
    }

    private void validatePrizeFormat(String prizeStr) {
        if (prizeStr == null || prizeStr.trim().isEmpty()) {
            throw new BusinessException("奖品不能为空");
        }

        String[] prizes = prizeStr.split("，");
        for (String prize : prizes) {
            Matcher matcher = PRIZE_PATTERN.matcher(prize.trim());
            if (!matcher.matches()) {
                throw new BusinessException("奖品格式错误，应为'数量个名称'格式: " + prize);
            }
        }
    }

    private void updateMaterialStock(String prizeStr, boolean isRollback) {
        String[] prizes = prizeStr.split("，");
        for (String prize : prizes) {
            Matcher matcher = PRIZE_PATTERN.matcher(prize.trim());
            if (matcher.matches()) {
                String name = matcher.group(2);
                int delta = Integer.parseInt(matcher.group(1)) * (isRollback ? 1 : -1);

                int affected = materialMapper.updateStock(name, delta);
                if (affected == 0) {
                    throw new BusinessException("物资不存在或库存不足: " + name);
                }
            }
        }
    }
}
